<template>
    <div class="boxMain">
        <div>
            <el-form :inline="true" :model="search" size="small" class="demo-form-inline">
                <el-form-item>
                    <el-input v-model="search.code" placeholder="编码" clearable />
                </el-form-item>
                <el-form-item>
                    <el-input v-model="search.name" placeholder="标题" clearable />
                </el-form-item>
                <el-form-item>
                    <el-input v-model="search.createUser" placeholder="创建人" clearable />
                </el-form-item>
                <el-form-item>
                    <el-date-picker v-model="search.createTime" type="date" value-format="YYYY-MM-DD" placeholder="创建时间"
                        clearable />
                </el-form-item>
                <el-form-item>
                    <el-select style="width: 80px;" v-model="search.isPay" placeholder="收费" clearable>
                        <el-option label="是" :value="true" />
                        <el-option label="否" :value="false" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-select style="width: 80px;" v-model="search.isDelete" placeholder="删除" clearable>
                        <el-option label="是" :value="true" />
                        <el-option label="否" :value="false" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="loadData">查询</el-button>
                    <el-button @click="resetLoadData()">重置</el-button>
                    <el-button type="primary" @click="openSaveDialog">新增</el-button>
                </el-form-item>
            </el-form>
            <el-table border :data="tableData" style="width: 100%;" height="700px">
                <el-table-column type="expand">
                    <template #default="scope">
                        <div style="text-indent: 2em;">
                            <p v-show="!scope.row.orign">原创地址：<el-link :href="scope.row.orignUrl" target="_blank">{{
                                scope.row.orignUrl }}</el-link></p>
                            <pre>简介:{{ scope.row.info }}</pre>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column type="selection" width="40"></el-table-column>
                <el-table-column label="编号" prop="code" width="180">
                    <template #default="scope">
                        <el-link type="primary" @click="findBookAndChapters(scope.row.id)">{{ scope.row.code }}</el-link>
                    </template>
                </el-table-column>
                <el-table-column label="标题" prop="name" min-width="100" show-overflow-tooltip />
                <el-table-column label="推荐" prop="hot" width="60" />
                <el-table-column label="收费" prop="isPay" width="60" />
                <el-table-column label="显示" prop="isShow" width="60" />
                <el-table-column label="原创" prop="orign" width="60" />
                <el-table-column label="定价" prop="price" width="100" />
                <el-table-column label="折扣" prop="discount" width="100" />
                <el-table-column label="售价" prop="retailPrice" width="100" />
                <el-table-column label="创建人" prop="createUser" width="80" />
                <el-table-column label="创建时间" prop="createTime" />
                <el-table-column label="更新时间" prop="updateTime" />
                <el-table-column label="删除" prop="isDelete" width="80" />
                <el-table-column label="设置" width="80" fixed="right" align="center">
                    <template #default="scope">
                        <el-link type="danger" @click="removeBook(scope.row.id)">删除</el-link>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="pageCss">
            <el-pagination v-model:current-page="search.page" v-model:page-size="search.size" :page-sizes="[5, 10, 30, 50]"
                small="small" background layout="total, sizes, prev, pager, next, jumper" :total="total"
                @change="loadData" />
        </div>
    </div>
    <!-- dialog -->
    <el-dialog draggable overflow v-model="saveDialog" title="Shipping address" width="80%" align-center destroy-on-close
        :close-on-click-modal="false" @closed="closedSaveDialog">
        <template #header>
            <span>保存{{ searchParams.name }}</span>
        </template>
        <div style="height: 600px;">
            <el-tabs v-model="activeTabName" tab-position="left" class="demo-tabs">
                <el-tab-pane label="文章" name="文章"
                    style="overflow-y: auto;height: 100%;display: flex;flex-direction: column;justify-content: space-between;">
                    <el-form label-width="80" ref="dataRef" :model="data" :rules="dataRules">
                        <el-form-item label="标题" prop="name">
                            <el-input v-model="data.name" autocomplete="off" />
                        </el-form-item>
                        <el-form-item label="图示" prop="img">
                            <el-upload style="line-height: 30px;" name="partFile" v-show="!img.imgName" class="upload-demo" :on-preview="handlePreview"
                                :action="config.fileUploadUrl+'/upload/file/upload?dirName=bookImg'" :on-success="successHandler">
                                <el-link type="primary">点击上传</el-link>
                            </el-upload>
                            <el-link v-show="img.imgName" @click="handlePreview">{{ img.imgName
                            }}</el-link>&ensp;<el-icon  v-show="img.imgName" class="closeImg" @click="beforeRemove">
                                <Close />
                            </el-icon>
                        </el-form-item>
                        <el-row>
                            <el-col :span="6">
                                <el-form-item label="推荐" prop="hot">
                                    <el-radio-group v-model="data.hot">
                                        <el-radio :label="true">是</el-radio>
                                        <el-radio :label="false">否</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="收费" prop="isPay">
                                    <el-radio-group v-model="data.isPay" @change="changePay">
                                        <el-radio :label="true">是</el-radio>
                                        <el-radio :label="false">否</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="显示" prop="isShow">
                                    <el-radio-group v-model="data.isShow">
                                        <el-radio :label="true">是</el-radio>
                                        <el-radio :label="false">否</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="原创" prop="orign">
                                    <el-radio-group @change="changeOrign" v-model="data.orign">
                                        <el-radio :label="true">是</el-radio>
                                        <el-radio :label="false">否</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="6">
                                <el-form-item label="定价(元)" prop="price">
                                    <el-input-number @change="changePrice" v-model="data.price" autocomplete="off"
                                        :precision="1" :min="0" :step="0.1" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="折扣" prop="discount">
                                    <el-input-number @change="changeDicount" v-model="data.discount" autocomplete="off"
                                        :disabled="!data.isPay" :precision="1" :step="0.1" :min="0" :max="10" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="售价(元)" prop="retailPrice">
                                    <el-input-number :controls="false" v-model="data.retailPrice" disabled :precision="2" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="排序" prop="sort">
                                    <el-input-number :controls="false" v-model="data.sort" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-form-item label="原始地址" prop="orignUrl">
                            <el-input :disabled="data.orign" v-model="data.orignUrl" autocomplete="off" />
                        </el-form-item>
                        <el-form-item label="简介" prop="info">
                            <el-input type="textarea" maxlength="300" show-word-limit
                                :autosize="{ minRows: 12, maxRows: 12 }" resize="none" v-model="data.info"
                                autocomplete="off" />
                        </el-form-item>
                    </el-form>
                    <div class="dialog-footer" style="display: flex;justify-content: right;align-items: flex-end;">
                        <el-button @click="saveDialog = false">取消</el-button>
                        <el-button :loading="subState" type="primary" @click="validataForm">
                            保存
                        </el-button>
                    </div>
                </el-tab-pane>
                <el-tab-pane label="章节" name="章节" style="height: 100%;">
                    <div style="display: flex;height: 100%;">
                        <div class="leftChapter">
                            <p class="editCss">
                            <div>列表</div>
                            <div class="handlerCss">
                                <el-icon @click="findChapters">
                                    <Refresh />
                                </el-icon>&ensp;
                                <el-icon>
                                    <Minus @click="removeChapter" />
                                </el-icon>&ensp;
                                <el-icon @click="addChapter">
                                    <Plus />
                                </el-icon>
                            </div>
                            </p>
                            <ul class="list-group list-group-flush" style="height: calc(100% - 20px);overflow-y: auto;">
                                <li @click="clickChapter(item)" @dblclick="dblclickChapter(item)"
                                    v-for="(item, index) in chapterList" :key="index"
                                    :class="{ active: item == clickChapterItem }"
                                    class="list-group-item d-flex justify-content-between align-items-center">
                                    <span v-if="item.selectChapterState"> {{ item.name }}</span>
                                    <span v-else><el-input v-model.trim="item.name"></el-input></span>&ensp;
                                    <span v-show="!item.selectChapterState" class="check badge bg-info rounded-pill"
                                        @click.stop="confimChapter(item, index)">
                                        <el-icon>
                                            <Check />
                                        </el-icon>
                                    </span>
                                </li>
                            </ul>
                        </div>
                        <div class="rightContent">
                            <p style="margin-bottom: 6px;">内容</p>
                            <div style="height: 88%;">
                                <v-md-editor @save="saveMd" v-model="content" height="100%"></v-md-editor>
                                <div style="display: flex;justify-content: flex-end;margin-top: 10px;">
                                    <el-button @click="saveDialog = false">取消</el-button>
                                    <el-button @click="saveMdContent" type="primary">保存</el-button>
                                </div>
                            </div>
                        </div>
                    </div>
                </el-tab-pane>
            </el-tabs>
        </div>
    </el-dialog>

    <!-- dialogImg -->
    <el-dialog id="imgDialog" draggable overflow v-model="dialogImg" width="210" align-center destroy-on-close
        :show-close="false">
        <template #header style="padding-bottom: 0px;">
        </template>
        <img :src="img.imgUrl" class="avatar" />
    </el-dialog>
</template>

<script>
import { ref } from "vue"
import utils from "@/common/utils"
import { dayjs } from "element-plus"
import config from "@/config/index.js"
export default {
    data() {
        return {
            config :config,
            searchParams: {},
            activeTabName: "文章",
            tableData: [],
            search: { page: 1, size: 10, name: "", code: "", createTime: null, isPay: null },
            saveDialog: false,
            data: { name: "", info: "", hot: true, isPay: false, price: 0, isShow: true, orign: false, discount: 0, retailPrice: 0 },
            dataRules: {
                name: [{ required: true }]
            },
            clickChapterItem: null,
            content: "",
            selectChapterState: true,
            subState: false,
            chapterList: [],
            total: 0,
            img: {
                // imgName: 'element-plus-logo.svg',
                // imgUrl: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
            },
            dialogImg: false
        }
    },
    created() {
        this.loadData()
    },
    methods: {
        findBookAndChapters(id) {
            this.$axios.get(`/blog/findBookAndChapters?id=${id}`).then(({ data }) => {
                if (data.code == 0) {
                    this.data = data.T
                    this.chapterList = data.T.chapterList
                    this.chapterList.forEach(x => x.selectChapterState = true)
                    this.saveDialog = true
                } else {
                    this.$message.error(data.msg)
                }
            }).catch(() => {
                this.$message.error("请求错误，请重试或联系管理员！")
            })
        },
        resetLoadData() {
            this.search = this.$options.data().search
            this.loadData()
        },
        loadData() {
            this.searchParams = utils.getHrefSeachParams()
            this.searchParams.name = decodeURI(this.searchParams.name)
            const search = { ...this.search, categoryName: this.searchParams.name }
            if (search.createTime) {
                search.createTime = dayjs(search.createTime).format("YYYY-MM-DD HH:mm:ss")
            }
            this.$axios.post(`/blog/page?page=${search.page}&size=${search.size}`, search).then(({ data }) => {
                if (data.code == 0) {
                    this.tableData = data.T.pages.records
                    this.total = data.T.pages.totalRow
                } else {
                    this.$message.error(data.msg)
                }
            }).catch(() => {
                this.$message.error("请求错误，请重试或联系管理员！")
            })
        },
        saveMdContent() {
            this.clickChapterItem.bookId = this.data.id
            this.saveMd(this.content, null)
        },
        removeBook(id) {
            this.$confirm("确认删除？", {
                distinguishCancelAndClose: true,
                confirmButtonText: '确认',
                cancelButtonText: '取消',
            }).then(() => {
                this.$axios.delete(`/blog/remove?id=${id}`).then(({ data }) => {
                    if (data.code == 0) {
                        this.loadData()
                    } else {
                        this.$message.error(data.msg)
                    }
                }).catch(() => {
                    this.$message.error("请求错误，请重试或联系管理员！")
                })
            }).catch(action => {
            });
        },
        saveMd(text, html) {
            let item = this.clickChapterItem
            console.log(item);
            if (!item) {
                this.$message.error("未选择章节")
                return
            }
            if (!item.selectChapterState) {
                this.$message.error("章节未保存")
                return
            }
            if (!text) {
                this.$message.error("未输入内容")
                return
            }
            let chapter = this.chapterList.find(x => x.name == item.name && x.sort == item.sort)
            chapter.content = text
            chapter.id = item.id
            this.$axios.post("/blog/saveChapterContent", chapter).then(({ data }) => {
                if (data.code == 0) {
                    this.$message.success(data.msg)
                } else {
                    this.$message.error(data.msg)
                }
            }).catch(() => {
                this.$message.error("请求错误，请重试或联系管理员！")
            })
        },
        openSaveDialog() {
            this.saveDialog = true
            let searchParams = utils.getHrefSeachParams()
        },
        closedSaveDialog() {
            this.$nextTick(() => {
                this.$refs.dataRef.resetFields()
                this.chapterList = []
                this.content = ""
                this.clickChapterItem = null
                this.data = this.$options.data().data
                this.activeTabName = "文章"
            })
        },
        async clickChapter(item) {
            this.clickChapterItem = item
            // let chapter = this.chapterList.find(x => x.name == item.name && x.sort == item.sort)
            let { data } = await this.findChapterContent(item.id)
            this.content = data.code == 0 ? (data.T ? data.T.content : "") : ""
        },
        async findChapterContent(chapterId) {
            return await this.$axios.get(`/blog/findChapterContent?chapterId=${chapterId}`)
        },
        async confimChapter(item, index) {
            if (!this.data.id) {
                this.$message.error("书籍未保存！")
                return true
            }
            item.selectChapterState = true
            // 
            if (!item.name) {
                item.name = "章节" + (index + 1)
            }
            console.log("保存章节:" + item.name);
            item.bookId = this.data.id
            this.$axios.post("/blog/saveChapter", item).then(({ data }) => {
                if (data.code == 0) {
                    this.$message.success(data.msg)
                    this.clickChapterItem.id = data.T.id
                } else {
                    this.$message.error(data.msg)
                }
            }).catch(() => {
                this.$message.error("请求错误，请重试或联系管理员！")
            })
        },
        dblclickChapter(item) {
            item.selectChapterState = false
        },
        changePay() {
            if (this.data.isPay) {
                this.data.discount = 10.0
                this.data.retailPrice = this.data.price * this.data.discount / 10
            } else {
                // this.data.price = 0.0
                this.data.discount = 0.0
                this.data.retailPrice = 0
            }
        },
        changeDicount(val) {
            val = val || 0
            let retailPrice = val * this.data.price / 10
            this.data.retailPrice = retailPrice
        },
        changeOrign(val) {
            if (!val) {
                this.data.orignUrl = ""
            }
        },
        changePrice(val) {
            val = val || 0
            let retailPrice = val * this.data.discount / 10
            this.data.retailPrice = retailPrice
        },
        validataForm() {
            this.subState = true
            this.$refs.dataRef.validate((validata) => {
                if (validata) {
                    this.builderData()
                    this.subState = false
                } else {
                    this.activeTabName = "文章"
                    this.subState = false
                }
            })
        },
        builderData() {
            this.activeTabName = "章节"
            this.data.categoryName = this.searchParams.name
            this.data.categoryId = this.searchParams.index.split("-")[1]
            this.data.imgName = this.img.imgName
            this.data.imgUrl = this.img.imgUrl
            this.$axios.post("/blog/save", this.data).then(({ data }) => {
                if (data.code == 0) {
                    this.data.id = data.T.id
                    this.loadData()
                } else {
                    this.$message.error(data.msg)
                }
            }).catch(() => {
                this.$message.error("请求错误，请重试或联系管理员！")
            })
        },
        async addChapter() {
            if (this.chapterList.some(x => !x.selectChapterState)) {
                this.clickChapterItem.id = null
                let flag = await this.confimChapter(this.clickChapterItem, this.chapterList.length - 1)
                if (flag) {
                    return
                }
            } else {
                this.chapterList.push({ selectChapterState: false, name: "", sort: this.chapterList.length + 1, content: "" })
                this.clickChapterItem = this.chapterList.at(-1)
                console.log(this.clickChapterItem);
            }
        },
        removeChapter() {
            let item = this.clickChapterItem
            if (!item) {
                this.$message.error("请选择需要删除的章节")
                return
            }
            let removeIndex = this.chapterList.findIndex(x => x.name == item.name && x.sort == item.sort)
            this.chapterList.splice(removeIndex, 1)
            this.$axios.delete(`/blog/removeChapter?chapterId=${item.id}`).then(({ data }) => {
                if (data.code == 0) {
                    this.$message.success(data.msg)
                } else {
                    this.$message.error(data.msg)
                }
            }).catch(() => {
                this.$message.error("请求错误，请重试或联系管理员！")
            })
            this.clickChapterItem = null
        },
        findChapters() {
            let bookId = this.data.id
            this.$axios.get(`/blog/findChapters?bookId=${bookId}`).then(({ data }) => {
                if (data.code == 0) {
                    this.chapterList = data.T
                    this.chapterList.forEach(x => x.selectChapterState = true)
                    this.clickChapterItem = null
                } else {
                    this.$message.error(data.msg)
                }
            }).catch(() => {
                this.$message.error("请求错误，请重试或联系管理员！")
            })
        },
        handlePreview(uploadFile) {
            this.dialogImg = true
        },
        beforeRemove() {
            this.$confirm(
                `确认删除图片 ${this.img.imgName} ?`
            ).then(
                () => {
                    this.img = {}
                }, () => {
                    console.log(false);
                }
            )
        },
        successHandler(res, file){
            if(res.code == 0){
                this.img = res
            }else{
                this.img = {imgName:"",imgUrl:""}
            }
        }
    }
}
</script>
<style scoped>
.my-header {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    gap: 16px;
}

#imgDialog>.el-dialog__header {
    padding-bottom: 0px !important;
}

.closeImg:hover {
    color: rgba(243, 12, 12, 0.842);
    cursor: pointer;
}
</style>
<style>
/* @import url(); 引入css类 */
.boxMain {
    height: 100%;
    /* overflow-y: auto; */
}

.pageCss {
    position: absolute;
    bottom: 0px;
    left: calc(100% - 70%);
    z-index: 100;
}

.leftChapter {
    width: 200px;
    height: 100%;
}

.el-tabs__content {
    height: 100% !important;
}

.rightContent {
    margin-left: 10px;
    width: calc(100% - 200px);
}

.editCss {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    margin: 0px 10px 5px 0px;
}

.handlerCss>.el-icon:hover {
    cursor: pointer;
    color: #1890ff;
}

.list-group>li:hover {
    background-color: #bebcbcda;
}

.check:hover {
    background-color: rgba(43, 247, 169, 0.973) !important;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>